<?php

	function generateString($length = 4) {
		$characters = '0123456789abcdefghijkmnopqrstuvxyzABCDEFGHJKLMNOPQRSTUVXYZ';
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, strlen($characters) - 1)];
		}
		return $randomString;
	}

	header("Content-type: image/png");
	
	function generateCaptcha($string, $width = 100, $height = 40, $bgSource = 'img/bg1.png'){
		$bgTxt = $bgSource;
		$img = imagecreatetruecolor($width, $height);
		$imgStr = imagecreatetruecolor($width, $height);
		$colorTransparent = imagecolorclosestalpha($imgStr, 255, 255, 255, 127);
		imagefill($imgStr, 0, 0, $colorTransparent);
		imagecolortransparent($imgStr, $colorTransparent);
		$bg = imagecreatefrompng($bgTxt);
		$bgInfo = getimagesize($bgTxt);
		$widthBg = $bgInfo[0];
		$heightBg = $bgInfo[1];
		$maxOffsetX = $widthBg - $width;
		$maxOffsetY = $heightBg - $height;
		$offsetX = rand(0, $maxOffsetX);
		$offsetY = rand(0, $maxOffsetY);
		imagecopyresampled($img, $bg, 0, 0, $offsetX, $offsetY, $width, $height, $width, $height);
		$txtColor = imagecolorexact($img, 0, 0, 255); // Цвет текста
		$fontSize = round($height / 2);
		$offesetTextY = round($height / 4);
		$lengthString = strlen($string);
		$part = round($width / $lengthString);
		
		for ($i=0; $i < $lengthString; $i++) { 
			$offesetTextX = $i * $part + round($part / 4);
			$angle = round(rand(-35, 35));
			imagefttext($imgStr, $fontSize, $angle, $offesetTextX, $offesetTextY + $fontSize, $txtColor, 'Gotham_Pro_Bold.ttf', $string[$i]);
		}
		
		setcookie("security_code", md5(mb_strtolower($string)));

		//imagefilter($imgStr, IMG_FILTER_SELECTIVE_BLUR);

		imagecopymerge($img, $imgStr, 0, 0, 0, 0, $width, $height, 100);

		imagepng($img);
		imagedestroy($img);

	}

	generateCaptcha(generateString(4), 250, 80);
	//generateCaptcha(generateString(4));
	/*250 100*/
?>